// Package business 包含相关的服务
// @author 5title_
// @date 2025-04-01

package business

import (
	"5title_gin/global"
	baseModel "5title_gin/internal/model"
	"5title_gin/internal/model/business/orders"
	"5title_gin/pkg/db/crud"
	"5title_gin/pkg/db/pagination"
	"fmt"
)

// OrdersService 服务
type OrdersService struct {
	crud *crud.CRUD[orders.Orders]
}

// NewOrdersService 创建服务实例
func NewOrdersService() *OrdersService {
	return &OrdersService{
		crud: crud.NewCRUD[orders.Orders](global.DB),
	}
}

// GetOrders 获取单个
func (s *OrdersService) GetOrdersById(id uint) (*orders.Orders, error) {
	model, err := s.crud.GetByID(id)
	if err != nil {
		return nil, fmt.Errorf("获取失败: %v", err)
	}
	return model, nil
}

// GetOrdersResponse 获取单个(响应对象)
func (s *OrdersService) GetOrdersResponse(id uint) (*orders.OrdersResponse, error) {
	model, err := s.GetOrdersById(id)
	if err != nil {
		return nil, err
	}

	// 转换为响应对象
	response := model.ToOrdersResponse()

	return response, nil
}

// GetOrdersList 获取列表
func (s *OrdersService) GetOrdersList(pageInfo baseModel.PageInfo) ([]*orders.Orders, int64, error) {
	// 分页查询
	list, total, err := pagination.QueryList[orders.Orders](orders.Orders{}, pagination.QueryOption{
		PageInfo: pageInfo,
		Debug:    true,
	})
	if err != nil {
		return nil, 0, fmt.Errorf("查询列表失败: %v", err)
	}

	return list, total, nil
}

// GetOrdersResponseList 获取列表(响应对象)
func (s *OrdersService) GetOrdersResponseList(pageInfo baseModel.PageInfo) ([]*orders.OrdersResponse, int64, error) {
	list, total, err := s.GetOrdersList(pageInfo)
	if err != nil {
		return nil, 0, err
	}

	// 转换为响应对象列表
	responseList := orders.ToOrdersResponseList(list)

	return responseList, total, nil
}

// CreateOrders 创建
func (s *OrdersService) CreateOrders(o *orders.Orders) error {
	return s.crud.Create(o)
}

// UpdateOrders 更新
func (s *OrdersService) UpdateOrders(o *orders.Orders) error {
	return s.crud.Update(o)
}

// DeleteOrders 删除
func (s *OrdersService) DeleteOrders(id uint) error {
	return s.crud.DeleteByID(id)
}

// GetOrdersByOrderNumber 根据订单号获取
func (s *OrdersService) GetOrdersByOrderNumber(orderNumber string) (*orders.Orders, error) {
	obj, err := s.crud.GetAll().Where("order_number = ?", orderNumber).First()
	if err != nil {
		return nil, fmt.Errorf("根据订单号获取失败: %v", err)
	}
	return obj, nil
}

// GetOrdersByUserName 根据用户名获取
func (s *OrdersService) GetOrdersByUserName(userName string) (*orders.Orders, error) {
	obj, err := s.crud.GetAll().Where("user_name = ?", userName).First()
	if err != nil {
		return nil, fmt.Errorf("根据用户名获取失败: %v", err)
	}
	return obj, nil
}
